﻿using System.Collections.Generic;
using System.Text;
using Core;
using Core.Event;
using Core.File;

namespace Game {
    public class WeaponBag : ISerializable<WeaponBag> {
        private List<Weapon> mWeaponList = new();

        public WeaponBag() { }

        public void AddWeapon(Weapon weapon) {
            mWeaponList.Add(weapon);
        }

        public void RemoveWeapon(Weapon weapon) {
            mWeaponList.Remove(weapon);
        }
        
        public Weapon GetWeapon(int index) {
            if (mWeaponList.Count == 0) {
                return null;
            }
            return mWeaponList[index % mWeaponList.Count];
        }

        public string Serialize() {
            //将武器列表序列化
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < mWeaponList.Count - 1; ++i) {
                builder.Append(mWeaponList[i].Serialize());
                //分隔符
                builder.Append("---");
            }

            if (mWeaponList.IsActive(mWeaponList.Count - 1)) {
                builder.Append(mWeaponList[mWeaponList.Count - 1].Serialize());   
            }
            return builder.ToString();
        }

        public void Deserialize(string data) {
            string[] readData = data.Split("---");
            for (int i = 0; i < readData.Length; ++i) {
                if (string.IsNullOrEmpty(readData[i])) {
                    continue; 
                }
                //生成武器
                Weapon weapon = Weapon.DeseralizeWeapon(readData[i]);
                weapon.AttachInstance(WeaponFactory.SpawnView(weapon,PlayerManager.Ins.CurPlayer.Component.WeaponBag));
                mWeaponList.Add(weapon);
            }
            
            if (mWeaponList.Count == 0) {
                Weapon weapon = WeaponFactory.New(WeaponID.WOODEN_SWORD);
                weapon.AttachInstance(WeaponFactory.SpawnView(weapon,PlayerManager.Ins.CurPlayer.Component.WeaponBag));
                mWeaponList.Add(weapon);
            }
        }
    }
}